import { createRouter, createWebHistory } from 'vue-router'
import { useUserStore } from '@/stores'
import nprogress from 'nprogress'
import 'nprogress/nprogress.css'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/login',
      component: () => import('@/views/login/LoginPage.vue')
    },
    {
      path: '/',
      component: () => import('@/views/layout/LayoutContainer.vue'),
      redirect: '/home',
      children: [
        {
          path: '/home',
          component: () => import('@/views/home/HomePage.vue')
        },
        {
          path: '/user',
          component: () => import('@/views/user/UserPage.vue')
        },
        {
          path: '/video',
          component: () => import('@/views/video/VideoPage.vue')
        },
        {
          path: '/article',
          component: () => import('@/views/article/ArticlePage.vue')
        },
        {
          path: '/comment',
          component: () => import('@/views/comment/CommentPage.vue')
        },
        {
          path: '/word',
          component: () => import('@/views/word/WordPage.vue')
        }
      ]
    }
  ]
})

// 全局路由前置导航守卫
router.beforeEach((to) => {
  nprogress.start()
  const userStore = useUserStore()
  if (!userStore.userInfo && to.path !== '/login') {
    return '/login'
  }
  nprogress.done()
})

// 全局路由后置导航守卫
router.afterEach(() => {
  nprogress.done()
})

export default router
